<script setup>
import {computed, onMounted, ref} from 'vue'
import http from "@/request/Http.js";
import {useRouter} from "vue-router";
import {ElMessage} from "element-plus";

// 查询参数（不含排序参数，前端本地排序）
const queryParams = ref({
  currentPage: 1,
  pageSize: 8,
  productName: '',
  categoryName: '',
})

const router = useRouter();

// 搜索框绑定值
const searchQuery = ref('')
// 选中的分类
const selectedCategory = ref('all')
// 排序方式：newest(最新)、priceAsc(价格升)、priceDesc(价格降)、viewCount(浏览量)、favoriteCount(收藏量)
const sortType = ref('newest')
// 原始商品列表（未排序）
const rawGoodsList = ref([])
// 排序后的商品列表（计算属性实时更新）
const sortedGoodsList = computed(() => {
  const list = [...rawGoodsList.value] // 复制数组避免修改源数据

  switch (sortType.value) {
    case 'newest':
      return list.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));
    case 'priceAsc':
      return list.sort((a, b) => (a.price || 0) - (b.price || 0));
    case 'priceDesc':
      return list.sort((a, b) => (b.price || 0) - (a.price || 0));
    case 'viewCount':
      return list.sort((a, b) => (b.viewCount || 0) - (a.viewCount || 0));
    case 'favoriteCount':
      return list.sort((a, b) => (b.favoriteCount || 0) - (a.favoriteCount || 0));
    default:
      return list;
  }
})
// 总条数
const total = ref(0)
// 加载状态
const loading = ref(false)
// 分类列表
const categoryList = ref([])

// 页面加载时初始化数据
onMounted(() => {
  fetchCategories()
  fetchGoodsList()
})

// 获取分类列表
const fetchCategories = async () => {
  try {
    const response = await http.get('/classify/getAllCategories')
    if (response.code === 200) {
      categoryList.value = response.data
    }
  } catch (error) {
    console.error('获取分类失败:', error)
  }
}

// 获取商品列表并更新收藏数
const fetchGoodsList = async () => {
  loading.value = true
  try {
    const params = new URLSearchParams(queryParams.value)
    const response = await http.get('/product/getGoodList?' + params.toString())
    if (response.code === 200) {
      rawGoodsList.value = response.data.records || []
      total.value = response.data.total || 0
      // 批量获取并更新收藏数
      await Promise.all(
          rawGoodsList.value.map(async (goods) => {
            try {
              const res = await http.get(`/FollowAndFavorite/getFavoriteCount?productId=${goods.id}`)
              if (res.code === 200) {
                goods.favoriteCount = res.data
              }
            } catch (err) {
              console.error(`获取商品${goods.id}收藏数失败:`, err)
              goods.favoriteCount = 0 // 失败时默认显示0
            }
          })
      )
    } else {
      ElMessage.error("获取商品列表失败：" + response.msg)
    }
  } catch (error) {
    ElMessage.error("获取商品列表出错：" + error.message)
  } finally {
    loading.value = false
  }
}

// 搜索商品
const handleSearch = () => {
  queryParams.value.currentPage = 1
  queryParams.value.productName = searchQuery.value
  fetchGoodsList()
}

// 分类筛选
const handleCategoryChange = (value) => {
  queryParams.value.currentPage = 1
  queryParams.value.categoryName = value === 'all' ? '' : value
  selectedCategory.value = value
  fetchGoodsList()
}

// 排序方式变更
const handleSortChange = (value) => {
  sortType.value = value
}

// 分页相关
const handleSizeChange = (val) => {
  queryParams.value.pageSize = val
  fetchGoodsList()
}
const handleCurrentChange = (val) => {
  queryParams.value.currentPage = val
  fetchGoodsList()
}

// 跳转到商品详情
const goToGoodDetail = async (id) => {
  try {
    await http.post(`/product/increaseViewCount/${id}`);
    const goods = rawGoodsList.value.find(item => item.id === id)
    if (goods) {
      goods.viewCount = (goods.viewCount || 0) + 1
    }
    await router.push(`/userHome/showGood/${id}`)
  } catch (error) {
    console.error('更新浏览量失败:', error)
    await router.push(`/userHome/showGood/${id}`)
  }
}

// 发布商品和求购
const handlePublish = () => {
  router.push('/userHome/addGood')
}
const handlePurchase = () => {
  router.push({path: '/userHome/Layout', query: {page: 'cart'}});
  console.log('跳转到购物车功能')
}
</script>

<template>
  <div class="home-page">
    <!-- 搜索区域 -->
    <div class="search-section">
      <h2>好看、好用、好玩，都在这里</h2>
      <el-input
          v-model="searchQuery"
          class="search-input"
          placeholder="搜索商品"
          style="width: 300px"
          @keyup.enter="handleSearch"
      >
        <template #append>
          <el-button icon="Search" type="primary" @click="handleSearch"></el-button>
        </template>
      </el-input>
    </div>

    <!-- 筛选和排序区域 -->
    <div class="filter-section">
      <div class="filters-container">
        <!-- 分类筛选 -->
        <el-select
            v-model="selectedCategory"
            class="filter-select"
            placeholder="全部"
            @change="handleCategoryChange"
        >
          <el-option label="全部" value="all"></el-option>
          <el-option
              v-for="category in categoryList"
              :key="category.id"
              :label="category.name"
              :value="category.name"
          ></el-option>
        </el-select>

        <!-- 排序下拉框 -->
        <el-select
            v-model="sortType"
            class="filter-select"
            placeholder="排序方式"
            style="margin-left: 10px;"
            @change="handleSortChange"
        >
          <el-option label="最新发布" value="newest"></el-option>
          <el-option label="价格从低到高" value="priceAsc"></el-option>
          <el-option label="价格从高到低" value="priceDesc"></el-option>
          <el-option label="浏览量从高到低" value="viewCount"></el-option>
          <el-option label="收藏量从高到低" value="favoriteCount"></el-option>
        </el-select>
      </div>

      <div class="action-buttons">
        <el-button type="primary" @click="handlePublish">发布商品</el-button>
        <el-button @click="handlePurchase">我的购物车</el-button>
      </div>
    </div>

    <!-- 商品列表 -->
    <el-skeleton v-if="loading" :count="8" class="goods-skeleton">
      <template #template>
        <div class="skeleton-item">
          <div class="skeleton-image"></div>
          <div class="skeleton-content">
            <div class="skeleton-title"></div>
            <div class="skeleton-price"></div>
            <div class="skeleton-meta"></div>
          </div>
        </div>
      </template>
    </el-skeleton>

    <div v-else class="goods-list">
      <el-card
          v-for="(goods, index) in sortedGoodsList"
          :key="goods.id || index"
          class="goods-card"
          @click="goToGoodDetail(goods.id)"
      >
        <el-carousel v-if="goods.images && goods.images.length" height="200px">
          <el-carousel-item v-for="(img, idx) in goods.images" :key="img.id || idx"> <!-- 优先使用图片ID作为key -->
            <img
                :alt="`${goods.name}-图片${idx+1}`"
                :src="img.imageUrl"
                class="goods-image"
                @error="e => e.target.src = 'https://picsum.photos/200/200'"
            />
          </el-carousel-item>
        </el-carousel>

        <!-- 无图片时显示默认图 -->
        <div v-else class="goods-image-container">
          <img
              alt="默认商品图片"
              class="goods-image"
              src="https://picsum.photos/200/200"
          />
        </div>
        <div class="goods-info">
          <h3 class="goods-title">{{ goods.name }}</h3>
          <p class="goods-price">¥{{ goods.price.toFixed(2) }}</p>
          <p class="goods-meta">
            {{ goods.viewCount || 0 }}人浏览 ·
            {{ goods.favoriteCount || 0 }}人收藏
          </p>
        </div>
      </el-card>

      <div v-if="sortedGoodsList.length === 0" class="empty-state">
        <el-empty description="暂无商品数据"></el-empty>
      </div>
    </div>

    <!-- 分页组件 -->
    <el-pagination
        v-model:current-page="queryParams.currentPage"
        v-model:page-size="queryParams.pageSize"
        :background="true"
        :page-sizes="[4, 8, 16, 20]"
        :total="total"
        layout="sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
  </div>
</template>

<style scoped>
/* 全局样式调整 */
.home-page {
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  background-color: #f9fafb;
  min-height: 100vh;
}

/* 搜索区域美化 */
.search-section {
  text-align: center;
  margin: 30px 0 40px;
  padding: 30px 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
}

.search-section h2 {
  margin-bottom: 20px;
  color: white;
  font-size: 28px;
  font-weight: 600;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.search-input {
  vertical-align: middle;
  border-radius: 30px !important;
  border: none;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.search-input:focus {
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15);
  border-color: #764ba2 !important;
}

/* 筛选和排序区域 */
.filter-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 25px;
  padding: 15px 20px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.filters-container {
  display: flex;
  align-items: center;
  gap: 15px;
}

.filter-select {
  width: 180px;
  border-radius: 6px;
  border-color: #e5e7eb;
}

.filter-select .el-input__wrapper {
  border-radius: 6px;
}

.action-buttons {
  display: flex;
  gap: 12px;
}

.action-buttons .el-button {
  border-radius: 6px;
  transition: all 0.2s ease;
  padding: 8px 18px;
}

.action-buttons .el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

/* 商品列表 */
.goods-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 25px;
  margin-bottom: 40px;
}

.goods-card {
  display: flex;
  flex-direction: column;
  background-color: white;
  border-radius: 10px;
  overflow: hidden;
  transition: all 0.3s ease;
  cursor: pointer;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  border: none;
}

.goods-card:hover {
  box-shadow: 0 12px 20px rgba(0, 0, 0, 0.1);
  transform: translateY(-5px);
}

/* 商品图片容器 */
.el-carousel {
  border-radius: 10px 10px 0 0;
  overflow: hidden;
}

.goods-image {
  width: 100%;
  height: 220px;
  object-fit: cover;
  transition: transform 0.5s ease;
}

.goods-card:hover .goods-image {
  transform: scale(1.05);
}

.goods-image-container {
  height: 220px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f3f4f6;
}

/* 商品信息区域 */
.goods-info {
  padding: 15px;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.goods-title {
  font-size: 16px;
  margin-bottom: 10px;
  font-weight: 500;
  color: #111827;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  height: 40px;
}

.goods-price {
  color: #ef4444;
  font-weight: 600;
  font-size: 18px;
  margin-bottom: 8px;
  margin-top: auto;
}

.goods-meta {
  font-size: 13px;
  color: #6b7280;
  display: flex;
  align-items: center;
  gap: 12px;
}

.goods-meta::before {
  content: "👁️";
  margin-right: 3px;
}

.goods-meta::after {
  content: "❤️";
  margin-left: 8px;
  margin-right: 3px;
}

/* 空状态和骨架屏 */
.empty-state {
  grid-column: 1 / -1;
  padding: 80px 0;
  text-align: center;
}

.goods-skeleton {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 25px;
  margin-bottom: 40px;
}

.skeleton-item {
  background-color: white;
  border-radius: 10px;
  padding: 0;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.skeleton-image {
  width: 100%;
  height: 220px;
  background-color: #f3f4f6;
  border-radius: 0;
  margin-bottom: 0;
}

.skeleton-content {
  padding: 15px;
}

.skeleton-title, .skeleton-price, .skeleton-meta {
  background-color: #f3f4f6;
  border-radius: 4px;
  margin-bottom: 10px;
  animation: shimmer 1.5s infinite;
}

@keyframes shimmer {
  0% {
    background-position: -200% 0;
  }
  100% {
    background-position: 200% 0;
  }
}

.skeleton-title {
  width: 85%;
  height: 18px;
}

.skeleton-price {
  width: 45%;
  height: 22px;
  margin-top: auto;
}

.skeleton-meta {
  width: 65%;
  height: 16px;
}

/* 分页组件 */
.el-pagination {
  display: flex;
  justify-content: center;
  margin-top: 30px;
  padding: 20px;
}

.el-pagination .el-pager li {
  border-radius: 4px;
  margin: 0 3px;
}

.el-pagination .el-pager li.active {
  background-color: #667eea;
  color: white;
}

.el-pagination .el-pager li:hover:not(.active) {
  color: #667eea;
}

/* 响应式调整 */
@media (max-width: 992px) {
  .goods-list {
    grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
  }

  .search-section h2 {
    font-size: 24px;
  }
}

@media (max-width: 768px) {
  .filter-section {
    flex-direction: column;
    align-items: stretch;
    gap: 15px;
  }

  .filters-container {
    width: 100%;
    justify-content: space-between;
  }

  .filter-select {
    width: 48%;
  }

  .action-buttons {
    justify-content: center;
  }

  .goods-image {
    height: 180px;
  }

  .goods-list {
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  }
}

@media (max-width: 576px) {
  .search-input {
    width: 100% !important;
  }

  .goods-list {
    grid-template-columns: 1fr 1fr;
  }

  .goods-title {
    font-size: 14px;
  }
}
</style>